function sendMessageEvent() {
    let messageInput = document.getElementById('messageInput');
    let messageText = messageInput.value.trim();
    if (messageText.length <= 0) {
        return;
    }
    sendMessageToServer(messageText);
    let userInfo = JSON.parse(ZhhSessionStorage_getItem('userInfo'));
    if (!userInfo) {
        userInfo = {
            userName: '游客',
            role: 4
        }
    }
    let userName = userInfo.userName;
    let role = userInfo.role;
    addMessageContent(true, messageText, userName, role);
    // 清空
    messageInput.value = '';
}

/**
 * @param isSelf 是否是自己发的消息
 * @param messageText 消息内容
 * @param userName 用户名
 * @param role 角色：1-黑色， 2-白色，3-观众
 */
function addMessageContent(isSelf, messageText, userName, role = 1) {
    // 显示消息体
    let messageList = document.getElementById('messageList');
    let messageDiv = document.createElement('div');
    messageDiv.classList.add('message');
    if (isSelf) {
        messageDiv.classList.add('self');
    } else {
        messageDiv.classList.add('other');
    }
    let messageContent = document.createElement('div');
    messageContent.className = 'message-content';
    let displayName = document.createElement("div");
    displayName.classList.add('userName');
    displayName.classList.add(isSelf ? 'selfUserName' : 'otherUsername');

    let un = document.createElement('span');
    un.innerText = userName;
    un.style.marginLeft = '5px';
    un.style.marginRight = '5px';
    let contentText = document.createElement("div");
    contentText.classList.add('message-text');
    if (isSelf) {
        contentText.classList.add('self');
    } else {
        contentText.classList.add('other');
    }
    contentText.innerText = messageText;
    if (role !== 0) {
        let avatar = document.createElement('div');
        let color = ''
        if (role === 1) {
            color = 'black';
        } else if (role === 2) {
            color = 'white';
        }
        avatar.className = `sl-${color}-chess`;
        if (isSelf) {
            displayName.appendChild(un);
            displayName.appendChild(avatar);
        } else {
            displayName.appendChild(avatar);
            displayName.appendChild(un);
        }
    } else {
        displayName.appendChild(un);
    }
    displayName.appendChild(document.createElement('p'));

    messageContent.appendChild(displayName);
    messageContent.appendChild(contentText);

    messageDiv.appendChild(messageContent);


    messageList.appendChild(messageDiv);

    // 滚动到底部
    scrollToBottom();
}

function addSystemMessageContent(messageText) {
    // 显示消息体
    let messageList = document.getElementById('messageList');
    let messageContent = document.createElement('div');
    messageContent.className = 'message system';
    let contentText = document.createElement("p");
    contentText.innerText = messageText;
    messageContent.appendChild(contentText);
    messageList.appendChild(messageContent);

    // 滚动到底部
    scrollToBottom();
}

function scrollToBottom() {
    let messages = document.getElementById('messageList');
    messages.scrollTop = messages.scrollHeight;
}


/**
 * 初始化界面内容
 */
function initializeTheDisplayContent() {
    // 初始化界面内容 开始
    let roomCode = ZhhSessionStorage_getItem("roomCode");
    createConnectionAndLoadWindow();
    if (roomCode != null) {
        addSystemMessageContent('当前房间码: ' + roomCode + '');
    }
    document.getElementById("roomCodeSpan").innerText = roomCode;
    // 初始化界面内容 结束
}

function addReadyButton() {
    let userInfoRole = JSON.parse(ZhhSessionStorage_getItem('userInfo'))?.role;
    if (userInfoRole === 0 || userInfoRole === undefined) {
        return;
    }
    let readyDiv = document.getElementById("ready");
    let readyButton = document.createElement("button");
    readyButton.innerText = "准备";
    readyButton.id = "readyButton";
    readyButton.className = 'ready-button';
    readyButton.addEventListener("click", function () {
        let roomCode = ZhhSessionStorage_getItem("roomCode");
        let userInfo = JSON.parse(ZhhSessionStorage_getItem("userInfo"));
        sendReadyMessage(roomCode, userInfo);
        changeReadyButton(userInfo);
    })
    readyDiv.appendChild(readyButton);
}

function sendReadyMessage(roomCode, userInfo) {
    if (roomCode == null || userInfo == null) {
        console.error("roomCode或userInfo为空")
    }
    let code = 2;
    sendSystemToServer(roomCode, code, '玩家准备');
}

function changeReadyButton(userInfo) {
    if (already) {
        turnToNoReadyStats(userInfo);
    } else {
        turnToReadyStats(userInfo);
    }
    already = !already;
}

function turnToReadyStats(userInfo) {
    let role = userInfo.role;
    if (role === 1 || role === 2) {
        let readyButton = document.getElementById("readyButton");
        readyButton.disabled = true;
        readyButton.innerText = "已准备";
        readyButton.style.backgroundColor = "green";
    }
}

function turnToNoReadyStats(userInfo) {
    let role = userInfo.role;
    if (role === 1 || role === 2) {
        let readyButton = document.getElementById("readyButton");
        readyButton.disabled = false;
        readyButton.innerText = "准备";
        readyButton.style.backgroundColor = '';
    }
}

function displayLabelUser(bu, wu) {
    if (bu) {
        displayLabelBlackUser(bu);
    }
    if (wu) {
        displayLabelWhiteUser(wu);
    }
}

function displayLabelBlackUser(user) {
    if (user.role !== 1) {
        return;
    }
    let id = user.userId;
    let sId = JSON.parse(ZhhSessionStorage_getItem('userInfo'))?.userId;
    let label = document.getElementById('sl-black-name');
    let displayContent = user.userName;
    if (id === sId) {
        displayContent = '我方';
    }
    label.innerText = displayContent;
}

function displayLabelWhiteUser(user) {
    if (user.role !== 2) {
        return;
    }
    let id = user.userId;
    let sId = JSON.parse(ZhhSessionStorage_getItem('userInfo'))?.userId;
    let label = document.getElementById('sl-white-name');
    let displayContent = user.userName;
    if (id === sId) {
        displayContent = '我方';
    }
    label.innerText = displayContent;
}

function copyToClipboard(text) {
    if (navigator.clipboard && navigator.clipboard.writeText) {
        // 使用 Clipboard API
        navigator.clipboard.writeText(text).then(() => {
            popUpMessageShow('房间码已复制到剪切板');
        }).catch(err => {
            console.error('无法复制文本: ', err);
        });
    } else {
        // 使用旧的方法（适用于不支持 Clipboard API 的浏览器）
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        popUpMessageShow('房间码已复制到剪切板');
    }
}
